<template>
  <view class="generation-container 22222222">
    <!-- 当前代成员 -->
    <view
      class="person-node"
      :style="{ left: parentX + 'px', top: parentY + 'px' }"
      @click="handleClick"
    >
      <view class="person-card" :class="{ 'is-self': person.isSelf }">
        <view class="person-avatar">
          <text class="avatar-icon">{{ person.gender === 1 ? "👨" : "👩" }}</text>
        </view>
        <view class="person-info">
          <!-- INSERT_YOUR_CODE -->
          <text class="person-name">
            <view v-if="!person.firstName && !person.lastName">姓名</view>
            <view v-else>{{ person.firstName }}{{ person.lastName }}</view>
          </text>
          <view class="person-tags">
            <text class="tag" :class="person.gender === 1 ? 'male' : 'female'">
              {{ person.gender === 1 ? "男" : "女" }}
            </text>
            <text class="tag" :class="person.isAlive ? 'alive' : 'deceased'">
              {{ person.isAlive ? "在世" : "已故" }}
            </text>
            <text v-if="person.isSelf" class="tag self">本人</text>
            <text v-if="person.spouseCount > 0" class="tag spouse">
              配偶{{ person.spouseCount }}人
            </text>
            <text v-if="person.totalChildrenCount > 0" class="tag children">
              子女{{ person.totalChildrenCount }}人
            </text>
          </view>
        </view>
        <!-- 操作按钮 -->
        <!-- <view class="person-actions">
          <view v-if="showActionMenu" class="action-menu" @click.stop>
            <view class="menu-item" @click="handleAction('edit')">编辑</view>
            <view
              v-if="!person.parentId"
              class="menu-item"
              @click="handleAction('add-parent')"
            >添加父辈</view>
            <view class="menu-item" @click="handleAction('add-child')">添加子辈</view>
            <view class="menu-item" @click="handleAction('add-spouse')">添加配偶</view>
            <view
              v-if="isLeaf"
              class="menu-item delete"
              @click="handleAction('delete')"
            >删除</view>
          </view>
        </view> -->
      </view>
    </view>

    <!-- 配偶显示 -->
    <view v-if="person.spouseList && person.spouseList.length > 0" class="spouse-container">
      <!-- 配偶连接线：只连接第一个配偶 -->
      <view
        v-if="person.spouseList && person.spouseList.length > 0"
        class="spouse-connection-line"
        :style="getSpouseMainLineStyle()"
      ></view>

      <view
        v-for="(spouse, index) in person.spouseList"
        :key="spouse.id"
        class="spouse-node"
        :style="{ left: parentX + 120 + index * 80 + 'px', top: parentY + 'px' }"
        @click="handleSpouseClick(spouse)"
      >
        <view class="spouse-card">
          <view class="person-avatar">
            <text class="avatar-icon">{{ spouse.gender === 1 ? "👨" : "👩" }}</text>
          </view>
          <view class="person-info">
            <text class="person-name">{{ spouse.firstName }}{{ spouse.lastName }}</text>
            <view class="person-tags">
              <text class="tag" :class="spouse.gender === 1 ? 'male' : 'female'">
                {{ spouse.gender === 1 ? "男" : "女" }}
              </text>
              <text class="tag" :class="spouse.isAlive ? 'alive' : 'deceased'">
                {{ spouse.isAlive ? "在世" : "已故" }}
              </text>
              <text class="tag spouse">配偶</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 向上连接线（连接到父辈） -->
    <!-- <view v-if="person.parentId" class="parent-connection-line" :style="getParentConnectionLineStyle()"></view> -->

    <!-- 父节点到底部的竖线（连接到横线） -->
    <view
      v-if="children.length > 1"
      class="vertical-line-from-parent"
      :style="getVerticalLineFromParentStyle()"
    ></view>

    <!-- 横线（连接所有子节点上方） -->
    <view
      v-if="children.length > 1"
      class="horizontal-line-to-children"
      :style="getHorizontalLineToChildrenStyle()"
    ></view>

    <!-- 向下连接线（连接到子辈） -->
    <view v-if="children.length > 0" class="connection-lines">
      <view
        v-for="(child, index) in children"
        :key="child.id"
        class="connection-line"
        :style="getConnectionLineStyle(child, index)"
      ></view>
    </view>

    <!-- 子代成员 -->
    <view v-if="children.length > 0" class="children-container">
      <GenealogyGeneration
        v-for="(child, index) in children"
        :key="child.id"
        :person="child"
        :generation="generation + 1"
        :level="level + 1"
        :index="index"
        :parent-x="getChildX(index)"
        :parent-y="getChildY()"
        :family-members="familyMembers"
        @node-click="$emit('node-click', $event)"
        @action="handleChildAction"
      />
    </view>
  </view>
</template>

<script>
export default {
  name: "GenealogyGeneration",
  props: {
    person: {
      type: Object,
      required: true,
    },
    generation: {
      type: Number,
      default: 1,
    },
    level: {
      type: Number,
      default: 0,
    },
    index: {
      type: Number,
      default: 0,
    },
    parentX: {
      type: Number,
      default: 0,
    },
    parentY: {
      type: Number,
      default: 0,
    },
    familyMembers: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      showActionMenu: false,
    };
  },
  computed: {
    children() {
      // 优先使用嵌套的 children 属性
      if (this.person.children && this.person.children.length > 0) {
        return this.person.children;
      }
      // 如果没有嵌套结构，则从 familyMembers 中筛选（兼容旧数据）
      return this.familyMembers.filter((m) => m.parentId === this.person.id);
    },
    isLeaf() {
      // 没有子女才是叶子节点
      return !(this.children && this.children.length > 0);
    },
  },
  methods: {
    handleClick() {
      this.$emit("node-click", this.person);
    },

    handleSpouseClick(spouse) {
      this.$emit("node-click", spouse);
    },

    handleAction(action) {
      this.showActionMenu = false;
      this.$emit("action", { action, person: this.person });
    },

    handleChildAction(data) {
      this.$emit("action", data);
    },

    getChildX(index) {
      const baseX = this.parentX;
      const spacing = 250; // 增加间距
      const offset = (index - (this.children.length - 1) / 2) * spacing;
      return baseX + offset;
    },

    getChildY() {
      return this.parentY + 150; // 增加垂直间距
    },

    getConnectionLineStyle(child, index) {
      const nodeWidth = 100;
      const childX = this.getChildX(index) + nodeWidth / 2 - 1.5;

      if (this.children.length === 1) {
        // 只有一个子节点时，直接从父节点底部连接到子节点顶部
        const nodeHeight = 120;
        const startY = this.parentY + nodeHeight; // 父节点底部
        const childY = this.getChildY(); // 子节点顶部
        return {
          position: "absolute",
          left: childX + "px",
          top: startY + "px",
          width: "3px",
          height: childY - startY + "px",
          background: "linear-gradient(180deg, #409EFF 0%, #67C23A 100%)",
          zIndex: 6,
        };
      } else {
        // 多个子节点时，从横线连接到子节点顶部
        const horizontalLineY = this.parentY + 150; // 横线位置
        const childY = this.getChildY();
        const childTop = childY; // 子节点顶部
        return {
          position: "absolute",
          left: childX + "px",
          top: horizontalLineY + "px",
          width: "3px",
          height: childTop - horizontalLineY + "px", // 从横线到子节点顶部
          background: "linear-gradient(180deg, #409EFF 0%, #67C23A 100%)",
          zIndex: 6,
        };
      }
    },

    getParentConnectionLineStyle() {
      // 找到父辈节点
      const parent = this.familyMembers.find((m) => m.id === this.person.parentId);
      if (!parent) return {};

      // 简化处理：使用固定的向上连接线
      // 连接线从当前节点顶部中心向上延伸150px
      const lineLength = 150;
      const startX = this.parentX + 50; // 当前节点中心X
      const startY = this.parentY; // 当前节点顶部Y

      return {
        width: "10px",
        height: lineLength + "px",
        left: startX - 5 + "px", // 居中显示，减去线宽的一半
        top: startY - lineLength + "px", // 向上延伸
        transform: "none", // 不需要旋转，因为是垂直的
      };
    },

    getVerticalLineFromParentStyle() {
      // 父节点底部中心到横线
      const nodeWidth = 100,
        nodeHeight = 120;
      const startX = this.parentX + nodeWidth / 2 - 1.5; // 线宽3px
      const startY = this.parentY + nodeHeight;
      const horizontalLineY = this.parentY + 150; // 横线位置
      return {
        position: "absolute",
        left: startX + "px",
        top: startY + "px",
        width: "3px",
        height: horizontalLineY - startY + "px",
        background: "linear-gradient(180deg, #409EFF 0%, #67C23A 100%)",
        zIndex: 6,
      };
    },

    getHorizontalLineToChildrenStyle() {
      // 横线：连接所有子节点上方中心
      const nodeWidth = 100;
      const horizontalLineY = this.parentY + 150; // 横线位置
      const firstChildX = this.getChildX(0) + nodeWidth / 2;
      const lastChildX = this.getChildX(this.children.length - 1) + nodeWidth / 2;
      const left = Math.min(firstChildX, lastChildX);
      const width = Math.abs(lastChildX - firstChildX);
      return {
        position: "absolute",
        left: left + "px",
        top: horizontalLineY + "px",
        width: width + "px",
        height: "3px",
        background: "linear-gradient(90deg, #409EFF 0%, #67C23A 100%)",
        zIndex: 6,
      };
    },

    getSpouseMainLineStyle() {
      // 配偶连接线：从当前节点右侧到第一个配偶节点左侧的横线
      const currentNodeRight = this.parentX + 100; // 当前节点右边界
      const firstSpouseNodeLeft = this.parentX + 120; // 第一个配偶节点左边界
      const connectionY = this.parentY + 60; // 连  接线Y坐标（节点中心高度）

      // 确保连接线宽度为正数
      const lineWidth = Math.max(0, firstSpouseNodeLeft - currentNodeRight);

      console.log(`配偶连接线:`, {
        currentNodeRight,
        firstSpouseNodeLeft,
        lineWidth,
        connectionY,
      });

      return {
        position: "absolute",
        left: currentNodeRight + "px",
        top: connectionY + "px",
        width: lineWidth + "px",
        height: "3px",
        background: "linear-gradient(90deg, #409EFF 0%, #67C23A 100%)",
        zIndex: 7,
      };
    },
  },
};
</script>

<style scoped>
.generation-container {
  position: relative;
}

.person-node {
  position: absolute;
  width: 100px;
  height: 120px;
  z-index: 10;
}

.person-card {
  background: #fff;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  padding: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
}

.person-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.person-card.is-self {
  border-color: #409eff;
  background: linear-gradient(135deg, #e3f2fd 0%, #f0f8ff 100%);
}

.person-avatar {
  text-align: center;
  margin-bottom: 8px;
}

.avatar-icon {
  font-size: 32px;
}

.person-info {
  text-align: center;
}

.person-name {
  display: block;
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.person-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center;
}

.tag {
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 10px;
  font-weight: 500;
}

.tag.male {
  background: #e3f2fd;
  color: #1976d2;
}

.tag.female {
  background: #fce4ec;
  color: #c2185b;
}

.tag.alive {
  background: #e8f5e8;
  color: #2e7d32;
}

.tag.deceased {
  background: #f5f5f5;
  color: #666;
}

.tag.self {
  background: #fff3e0;
  color: #f57c00;
}

.tag.spouse {
  background: #f3e5f5;
  color: #7b1fa2;
}

.tag.children {
  background: #e8f5e8;
  color: #2e7d32;
}

.person-actions {
  position: absolute;
  top: 8px;
  right: 8px;
}

.action-btn {
  background: none;
  border: none;
  font-size: 16px;
  color: #888;
  padding: 4px;
  border-radius: 4px;
  cursor: pointer;
}

.action-btn:hover {
  background: #f0f0f0;
}

.action-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  min-width: 120px;
}

.menu-item {
  padding: 8px 12px;
  font-size: 12px;
  color: #333;
  cursor: pointer;
  transition: background 0.2s;
}

.menu-item:hover {
  background: #f5f7fa;
  color: #409eff;
}

.menu-item.delete {
  color: #f44336;
}

.menu-item.delete:hover {
  background: #ffebee;
}

.spouse-container {
  position: absolute;
  z-index: 8;
}

.spouse-node {
  position: absolute;
  width: 80px;
  height: 100px;
}

.spouse-card {
  background: #fff;
  border: 2px solid #e0e0e0;
  border-radius: 10px;
  padding: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
}

.spouse-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
}

.spouse-connection-line {
  position: absolute;
  height: 3px;
  background: linear-gradient(90deg, #409eff 0%, #67c23a 100%);
  border-radius: 2px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  z-index: 7;
}

.connection-lines {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 5;
}

.connection-line {
  position: absolute;
  height: 3px;
  background: linear-gradient(90deg, #409eff 0%, #67c23a 100%);
  border-radius: 2px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.parent-connection-line {
  position: absolute;
  width: 10px;
  background: linear-gradient(180deg, #409eff 0%, #67c23a 100%);
  border-radius: 5px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  z-index: 5;
}

.vertical-line-from-parent {
  position: absolute;
  width: 3px;
  background: linear-gradient(180deg, #409eff 0%, #67c23a 100%);
  border-radius: 2px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  z-index: 6;
}

.horizontal-line-to-children {
  position: absolute;
  width: 100%; /* 横线宽度等于父节点宽度 */
  height: 3px;
  background: linear-gradient(90deg, #409eff 0%, #67c23a 100%);
  border-radius: 2px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  z-index: 6;
}

.children-container {
  position: relative;
}
</style>
